package com.dlc.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dlc.shop.bean.dto.AllotOrderItemDTO;
import com.dlc.shop.bean.model.AllotOrderItem;
import com.dlc.shop.common.constants.SegmentIdKey;
import com.dlc.shop.dao.AllotOrderItemMapper;
import com.dlc.shop.service.AllotOrderItemService;
import com.dlc.shop.service.SegmentService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gaozijie
 * @since 2023-11-20
 */
@Service
@AllArgsConstructor
public class AllotOrderItemServiceImpl extends ServiceImpl<AllotOrderItemMapper, AllotOrderItem> implements AllotOrderItemService {

    private final SegmentService segmentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBatchAllotOrderItem(List<AllotOrderItemDTO> allotOrderItemDTOList) {
        if (CollectionUtils.isEmpty(allotOrderItemDTOList)) {
            return;
        }
        List<AllotOrderItem> allotOrderItems = new ArrayList<>(allotOrderItemDTOList.size());
        AllotOrderItem allotOrderItem;
        for (AllotOrderItemDTO allotOrderItemDTO : allotOrderItemDTOList) {
            allotOrderItem = this.buildAllotOrderItem(allotOrderItemDTO);
            allotOrderItems.add(allotOrderItem);
        }
        this.saveBatch(allotOrderItems);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchAllotOrderItem(List<AllotOrderItemDTO> allotOrderItemDTOList) {
        if (CollectionUtils.isEmpty(allotOrderItemDTOList)) {
            return;
        }
        List<AllotOrderItem> allotOrderItems = allotOrderItemDTOList.stream().map(x -> {
            AllotOrderItem allotOrderItem = new AllotOrderItem();
            BeanUtils.copyProperties(x, allotOrderItem);
            allotOrderItem.setUpdateTime(LocalDateTime.now());
            return allotOrderItem;
        }).toList();
        this.updateBatchById(allotOrderItems);
    }

    /**
     * 构建调拨订单商品实体类
     * @param allotOrderItemDTO 调拨订单商品dto
     * @return 调拨订单商品
     */
    private AllotOrderItem buildAllotOrderItem(AllotOrderItemDTO allotOrderItemDTO) {
        AllotOrderItem allotOrderItem = new AllotOrderItem();
        BeanUtils.copyProperties(allotOrderItemDTO, allotOrderItem);
        allotOrderItem.setAllotOrderItemId(segmentService.getDateFormatSegmentId(SegmentIdKey.ALLOT_ORDER));
        allotOrderItem.setAllotInCount(0);
        allotOrderItem.setCreateTime(LocalDateTime.now());
        allotOrderItem.setUpdateTime(LocalDateTime.now());
        return allotOrderItem;
    }
}
